﻿using System;
using System.Collections.Generic;

namespace Odyssey
{
    public static class HighPerformanceExtension
    {
        public static int IndexOfBySpan(this string contentString, string indexOfString, StringComparison stringComparer = StringComparison.CurrentCultureIgnoreCase)
        {
            var contentSpan = contentString.AsSpan();
            var indexOfSpan = indexOfString.AsSpan();
            return contentSpan.IndexOf(indexOfSpan, stringComparer);
        }

        public static string SubStringBySpan(this string contentString, int length, int start = 0)
        {
            var contentSpan = contentString.AsSpan();
            return contentSpan.Slice(start, length).ToString();
        }

        public static List<string> SplitBySpan(this string contentString, char spiltChar)
        {
            return SplitBySpan(contentString, new ReadOnlySpan<char>(new[] { spiltChar }));
        }

        public static List<string> SplitBySpan(this string contentString, string spiltString)
        {
            return SplitBySpan(contentString, spiltString.AsSpan());
        }

        private static List<string> SplitBySpan(string contentString, ReadOnlySpan<char> splitSpan)
        {
            var contentSpan = contentString.AsSpan();
            var splitIndex = 0;
            var splitList = new List<string>();
            while (true)
            {
                splitIndex = contentSpan.IndexOf(splitSpan);
                if (splitIndex > -1)
                {
                    splitList.Add(contentSpan.Slice(0, splitIndex).ToString());
                    contentSpan = contentSpan.Slice(splitIndex, contentSpan.Length);
                }
                else
                {
                    break;
                }
            }
            return splitList;
        }
    }
}
